//
//  JkmHomeTableViewController.swift
//  SinaWb
//
//  Created by Jiang on 16/5/8.
//  Copyright © 2016年 Jiang. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit
class JkmHomeTableViewController: JkmBaseTableViewController{
    
    //是否为最后一行的标记
    var isLast = false
    
    //微博信息数组
    var Status : Array<[String : AnyObject]>?
    
    //行高缓存
    var hightCaches =  [String : CGFloat]()
    
    //标题按钮弹出动画的控制器
    let PresentAnimationManager :JkmPresentationAniamtionManager = {
        //设置弹出菜单的位置和大小
        let managers = JkmPresentationAniamtionManager()
        let screen = UIScreen.mainScreen().bounds
        let w = screen.size.width
        let h = screen.size.height
        managers.viewFrame = CGRect(x: w * 0.25 , y: 60, width: w * 0.5, height: h * 0.25)
        return managers
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置提示栏
        let navigationBar = navigationController?.navigationBar
        navigationBar?.insertSubview(infoLable, atIndex: 0)
        infoLable.snp_makeConstraints { (make) in
            make.left.equalTo(navigationBar!.snp_left)
            make.bottom.equalTo(navigationBar!.snp_bottom)
            make.width.equalTo(navigationBar!.snp_width)
            make.height.equalTo(30)
        }
        infoLable.alpha = 0
        //设置刷新提示区
        refreshControl = JkmRefreshControl()
            
        refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: .ValueChanged)

        //判断是否登录
        if !ViewModel.sharViewModel.userLogin {
            self.Visitor?.setCircleImageAndTextContent(nil, text: "关注一些人，回这里看看有什么惊喜")
            return
        }
        // 载入数数据
        loadData()
        
        tableView.separatorStyle = .None

        //设置左右按钮和标题按钮
        setNav()
        //注册通知
        addobservers()
    }
    
    //MARK:数据加载( 1.正常加载 2.下拉刷新  3.下拉刷新)
    @objc private  func loadData(){
        
        HomeViewModel.sharViewModel.loadData(isLast, Complete: {(count,status) in
            
            self.refreshControl?.endRefreshing()
            
            self.infoLableAnimation(Count: count)
            
            self.Status = status
            
            self.isLast = false
            
            self.tableView.reloadData()
            
            }, Wrong: { (error) in
                
                JkLog(error)
                
                self.refreshControl?.endRefreshing()
                self.infoLableAnimation(Count: -1)
        })

    }
    
    //MARK:刷新提示栏动画
    private  func infoLableAnimation(Count count:Int) {

        infoLable.text = (count == 0) ? "没有新的微博" : "更新\(count)条微博"
        if count < 0 {
            infoLable.text = "加载失败"
        }
        UIView.animateWithDuration(1, animations: {
             self.infoLable.transform = CGAffineTransformMakeTranslation(0, 30)
            self.infoLable.alpha = 0.7
            }) { (_) in
                    UIView.animateWithDuration(1, delay: 2, options: UIViewAnimationOptions.init(rawValue: 0), animations: {
                          self.infoLable.transform = CGAffineTransformIdentity
                            self.infoLable.alpha = 0
                        }, completion: { (_) in
                    })
        }
    
    }
    
    
    
    //MARK:TableView数据代理
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Status?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let data = CellDataModel(dictionary: Status![indexPath.row])
        if indexPath.row == Status!.count - 1 {
            isLast = true
            loadData()
        }
        
        let cell = getTheCell(data, tableView: tableView)
        cell?.status = JkmCellStatus(data: data)
                
        return cell!
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        let data = CellDataModel(dictionary: Status![indexPath.row])
        let ids = data.id as! Int

        if let hight = hightCaches["\(ids)"] {
            return hight
        }
        
        let cell = getTheCell(data, tableView: tableView)
        let hight = cell!.getTheHight(JkmCellStatus(data: data))
        
        hightCaches.updateValue(hight, forKey: "\(ids)")
        
        return hight
    }
    
   private func getTheCell(data:CellDataModel,tableView: UITableView)->BaseCell?{
        
        var id = "Cell"
        if data.retweeted_status != nil{
            id = "forward"
        }
        
        var cell = tableView.dequeueReusableCellWithIdentifier(id) as? BaseCell
        
        if cell == nil {
            
            if data.retweeted_status == nil{
                
                cell =  JkmHomeTableViewCell(style: .Default, reuseIdentifier: id)
            }else{
                
                cell = JkmForwardCell(style: .Default, reuseIdentifier: id)
            }
            
        }
        return cell
    }
    
    //提示栏
    private var infoLable : UILabel = {
        let lable = UILabel()
        lable.textAlignment = .Center
        lable.font = UIFont.systemFontOfSize(14)
        lable.backgroundColor = UIColor.orangeColor()
        lable.textColor = UIColor.whiteColor()
        return lable
    }()
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
}



// MARK: - 按钮操作
extension JkmHomeTableViewController{
    
    
    //注册接收菜单窗口背景点击的通知
    private func addobservers(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ClickbackGround), name: PresentationControlelrClickBackGroundButton, object: nil)

    }
    //设置按钮
    private func setNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(ImageName: "navigationbar_friendattention", target: self, selector: #selector(ClickLtbutton))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(ImageName: "navigationbar_pop", target: self, selector: #selector(ClickRtbutton))
        
        
        navigationItem.titleView = JkmTitleButton(title: (ViewModel.sharViewModel.UserInfo?.name)!+"  ", target: self, selector: #selector(ClickTitleButton))
    }
    
    //右侧按钮监听
    @objc private func ClickRtbutton(){
        
        let QrView = JkmQRCodeViewController()
        
        let navi  = UINavigationController(rootViewController: QrView)
    
        presentViewController(navi, animated: true, completion: nil)
    }
    
    //左侧按钮监听
    @objc  private func ClickLtbutton(){
        JkLog(" ")
    }
    
    //弹出菜单栏点击背景
    @objc private func ClickbackGround(){
        
        let a = navigationItem.titleView as! UIButton
        
        a.selected = !a.selected
        
    }
    
    //编辑标题按钮
    @objc private  func ClickTitleButton(sender : UIButton){
        sender.selected = !sender.selected
        
        let menu = JkmTitleMenuController()
        
        menu.transitioningDelegate = PresentAnimationManager
        
        menu.modalPresentationStyle = .Custom
        
        presentViewController(menu, animated: true, completion: nil)
        
    }
    
}


